<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>班级管理</el-breadcrumb-item>
      <el-breadcrumb-item>学生列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索 添加 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入班级名称"
            v-model="queryInfo.query"
            clearable
            @clear="gatStudentList"
            @keydown.enter.native="getOneByStudentId"
          >
            <el-button slot="append" icon="el-icon-search" @click="getOneByStudentId"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addClassDialogVisible = true">添加学生</el-button>
        </el-col>
      </el-row>
      <!-- 班级列表区域 -->
      <el-table :data="studentList" border stripe>
        <!-- stripe: 斑马条纹
        border：边框-->
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="stuId" label="学号"></el-table-column>
        <el-table-column prop="stuName" label="学生姓名"></el-table-column>
        <el-table-column prop="classId.classid" label="所属班级"></el-table-column>
        <el-table-column prop="classId.grade" label="年级"></el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              circle
              @click="showEditDialog(scope.row.stuId)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              circle
              @click="removeById(scope.row.stuId)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <!-- <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNo"
        :page-size="queryInfo.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
      ></el-pagination> -->
    </el-card>

    <!-- 添加班级的对话框 -->
    <el-dialog
      title="添加学生"
      :visible.sync="addClassDialogVisible"
      width="30%"
      @close="addDialogClosed"
      @keydown.enter.native="add"
    >
      <!-- 内容主体 -->
      <el-form :model="addStudentForm" ref="addStudentFormRef" :rules="addStudentFormRules" label-width="100px">
        <el-form-item label="学号" prop="stuId">
          <el-input v-model="addStudentForm.stuId"></el-input>
        </el-form-item>
        <el-form-item label="学生姓名" prop="stuName">
          <el-input v-model="addStudentForm.stuName"></el-input>
        </el-form-item>
        <el-form-item label="所属班级" prop="classId">
          <el-input v-model="addStudentForm.classId"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addStudentForm.password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addClassDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改学生的对话框 -->
    <el-dialog
      title="修改学生信息"
      :visible.sync="editStudentDialogVisible"
      width="40%"
      @close="editDialogClosed"
      @keydown.enter.native="editUser"
    >
      <!-- 内容主体 -->
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="80px">
        <el-form-item label="学号" prop="stuId">
          <el-input v-model="editForm.stuId"></el-input>
        </el-form-item>
        <el-form-item label="学生姓名" prop="stuName">
          <el-input v-model="editForm.stuName"></el-input>
        </el-form-item>
        <!-- TODO  -->
        <el-form-item label="所属院系" prop="deptId">
          <el-select v-model="editFormAboutClass.college" placeholder="请选择">
            <!-- <el-option
              v-for="item in deptList"
              :key="item.id"
              :label="item.college"
              :value="item.id"
            >
            </el-option> -->
            <el-option label="计算机" value="计算机" college="计算机"></el-option>
            <el-option label="机械" value="机械" college="服装"></el-option>
            <el-option label="服装" value="服装" college="机械"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属班级" prop="classId">
          <el-input v-model="editFormAboutClass.classid"></el-input>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="editFormAboutClass.major"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.stuPhone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.stuEmail"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editStudentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-z0-9_-]+)@([\da-z-]+)\.([a-z]{2,6})$/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 院系列表
      studentList: [],
      deptList: [],
      // 获取班级列表查询参数对象
      queryInfo: {
        query: ''
        // 当前页数
        //pageNo: 1,
        // 每页显示多少数据
        // pageSize: 5
      },
      // 添加班级对话框
      addClassDialogVisible: false,
      // 班级添加
      addStudentForm: {
        stuId: '',
        stuName: '',
        classId: '',
        password: ''
      },
      // 学生添加表单验证规则
      addStudentFormRules: {
        stuId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
        classId: [{ required: true, message: '请输入班级编号', trigger: 'blur' }],
        stuName: [{ required: true, message: '学生姓名', trigger: 'blur' }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 30, message: '密码太短', trigger: 'blur' }
        ]
      },
      // 修改学生信息
      editStudentDialogVisible: false,
      editForm: {},
      editFormAboutClass: {},
      // 编辑学生表单验证
      editFormRules: {
        // classid: [{ required: true, message: '请输入学号', trigger: 'blur' }],
        // major: [{ required: true, message: '请输入专业名称', trigger: 'blur' }],
        // stuId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
        // classId: [{ required: true, message: '请输入班级编号', trigger: 'blur' }],
        // stuName: [{ required: true, message: '学生姓名', trigger: 'blur' }],
        // email: [
        //   { required: true, message: '请输入邮箱', trigger: 'blur' },
        //   { validator: checkEmail, trigger: 'blur' }
        // ],
        // phone: [
        //   { required: true, message: '请输入电话', trigger: 'blur' },
        //   { validator: checkMobile, trigger: 'blur' }
        // ]
      }
    }
  },
  created() {
    this.gatStudentList()
  },
  methods: {
    async gatStudentList() {
      console.log('gatStudentList被调用')
      const { data: res } = await this.$axios.get('/api/admin//getStudentAll')
      console.log(res)
      if (!res) {
        return this.$message.error('获取班级列表失败！')
      }
      this.$message.success('获取班级列表成功')
      this.studentList = res
    },
    async getDeptList() {
      const { data: res } = await this.$http.get('/api/admin/getClassInfoAll')
      if (!res) {
        return this.$message.error('获取院系列表失败！')
      }
      this.deptList = res
    },
    // 监听 添加学生对话框的关闭事件
    addDialogClosed() {
      //this.$refs.addStudentFormRef.resetFields()
    },
    // 添加学生
    add() {
      // 提交请求前，表单预验证
      this.$refs.addStudentFormRef.validate(async (valid) => {
        console.log(this.addStudentForm)
        // 表单预校验失败
        if (!valid) return
        const { data: res } = await this.$axios.post('/api/admin//insertStudentInfo', {
          classId: {
            classid: this.addStudentForm.classId
          },
          stuId: this.addStudentForm.stuId,
          stuName: this.addStudentForm.stuName,
          stuPassword: this.addStudentForm.password
        })
        console.log(res)
        if (!res) {
          this.$message.error('添加学生失败！')
          return
        }
        console.log(res)
        this.$message.success('添加学生成功！')
        // 隐藏添加班级对话框
        this.addClassDialogVisible = false
        this.gatStudentList()
      })
    },
    // 编辑学生信息
    async showEditDialog(stuId) {
      this.editStudentDialogVisible = true
      console.log('stuId', stuId)
      const { data: res } = await this.$axios.get('/api/admin/getStudent', {
        params: {
          id: stuId
        }
      })
      console.log('fdsafsd', res)

      // console.log(this.editForm[classId].classid)
      // console.log(res.classId.college)
      // if (!res) {
      //   return this.$message.error('查询学生信息失败！')
      // }
      this.editForm = res
      this.editFormAboutClass = res.classId
      console.log(this.editForm)
      console.log(this.editFormAboutClass)
      // this.editForm.classId = res.classId.classid
      // this.editForm.grade = res.classId.grade
      // this.editForm.major = res.classId.major
      // this.editStudentDialogVisible = true
    },
    // 监听修改学生对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改学生信息
    async editUser() {
      // 提交请求前，表单预验证
      // this.$refs.editFormRef.validate(async (valid) => {
      //   // console.log(valid)
      //   // 表单预校验失败
      //   console.log('this.=======', this.editForm)
      //   console.log(this.editFormAboutClass)
      //   if (!valid) return console.log(valid)
      //   const { data: res } = await this.$axios.post('/api/admin//newStudentInfo', {
      //     stuId:this.editForm.stuId,
      //     phone:this.editFormAboutClass.phone
      //   })
      //   console.log('sjdkla', res)
      //   if (!res) {
      //     this.$message.error('更新班级信息失败！')
      //   }
      //   // 隐藏添加班级对话框
      //   this.editStudentDialogVisible = false
      //   this.$message.success('更新班级信息成功！')
      //   this.gatStudentList()
      // })
      console.log(this.editForm)
      console.log(this.editFormAboutClass)
      const { data: res } = await this.$axios.post('/api/admin//newStudentInfo', {
        stuId: this.editForm.stuId,
        stuPhone: this.editForm.stuPhone,
        classId: {
          classid: this.editFormAboutClass.classid
        },
        stuEmail: this.editForm.stuEmail
      })
      console.log('sjdkla', res)
      if (!res) {
        this.$message.error('更新班级信息失败！')
      }
      // 隐藏添加班级对话框
      this.editStudentDialogVisible = false
      this.$message.success('更新班级信息成功！')
      this.gatStudentList()
    },
    // 删除学生
    async removeById(stuId) {
      console.log('stuId', stuId)
      const confirmResult = await this.$confirm('确定删除该学生?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$axios.get('/api/admin/deleteStudent', {
        params: {
          stuId
        }
      })
      console.log(res)
      if (res !== 1) return this.$message.error('删除学生失败！')
      this.$message.success('删除成功！')
      this.addClassDialogVisible = false
      // 重新获取用户列表数据
      this.gatStudentList()
    },
    // 根据学生id查询
    async getOneByStudentId() {

      if (this.queryInfo.query !== null) {
        const { data: res } = await this.$axios.get('/api/admin/getStudent', {
          params: {
            id: this.queryInfo.query
          }
        })
        console.log(res)
        this.studentList = [res]
        this.$message.success('查找成功')
      } else {
        this.$message.error('查找失败')
      }
    }
  }
}
</script>
<style lang="less" scoped></style>
